

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言作为最经典的WebUI自动化工具库，想必只要是从事软件测试行业的人都听说过它的名字–selenium。 根据目前的就业情况来看，selenium相关的知识已经成为面试中高频出现的面试题。 本章节，就介绍一下selenium的相关内容：  工作原理 基本使用 自动化-PO模式 面试常问  工作原理selenium工作原理，很多测试工程师、测试开发可能都不知道，因为它在实际的自动化测试用例编写中，">
<meta property="og:type" content="article">
<meta property="og:title" content="selenium--最为流行的WebUI自动化工具库">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/09/18/autoTest/selenium/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言作为最经典的WebUI自动化工具库，想必只要是从事软件测试行业的人都听说过它的名字–selenium。 根据目前的就业情况来看，selenium相关的知识已经成为面试中高频出现的面试题。 本章节，就介绍一下selenium的相关内容：  工作原理 基本使用 自动化-PO模式 面试常问  工作原理selenium工作原理，很多测试工程师、测试开发可能都不知道，因为它在实际的自动化测试用例编写中，">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-09-18T05:26:44.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.246Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="自动化测试">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="WebUI自动化">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>selenium--最为流行的WebUI自动化工具库 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="selenium--最为流行的WebUI自动化工具库"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-09-18 13:26" pubdate>
          2022年9月18日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.3k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">selenium--最为流行的WebUI自动化工具库</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>作为最经典的WebUI自动化工具库，想必只要是从事软件测试行业的人都听说过它的名字–<strong>selenium</strong>。</p>
<p>根据目前的就业情况来看，selenium相关的知识已经成为面试中高频出现的面试题。</p>
<p>本章节，就介绍一下selenium的相关内容：</p>
<ul>
<li>工作原理</li>
<li>基本使用</li>
<li>自动化-PO模式</li>
<li>面试常问</li>
</ul>
<h1 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h1><p>selenium工作原理，很多测试工程师、测试开发可能都不知道，因为它在实际的自动化测试用例编写中，确实没有应用的地方。但是，在一些高薪的岗位中，有可能会出现它的身影。</p>
<p>那么为什么用不到，但面试却要问呢？问这个知识点的面试官，想考察的是：<strong>对技术的追求程度，想看看你是否偏好去追溯原理性的知识。</strong></p>
<p>在这个内卷的环境，这种想法其实已经见怪不怪了，<strong>学就完事了</strong>。</p>
<h2 id="WebDriver"><a href="#WebDriver" class="headerlink" title="WebDriver"></a>WebDriver</h2><p>所有对浏览器的操作，都是通过一个协议–<strong>WebDriver</strong>。</p>
<p>WebDriver会根据浏览器提供的api，将这些api封装成一个个函数，供使用者使用。比如我们常见的：</p>
<ul>
<li>find_element</li>
<li>send_keys</li>
<li>click</li>
</ul>
<p>WebDriver甚至可以直接操作浏览器本身，比如：</p>
<ul>
<li>让浏览器窗口最大化</li>
<li>无头浏览器</li>
</ul>
<h3 id="弊端"><a href="#弊端" class="headerlink" title="弊端"></a>弊端</h3><p>WebDriver是基于浏览器厂商提供的<strong>驱动</strong>来调动浏览器本身，像谷歌浏览器的ChromeDriver/火狐浏览器的FirefoxDriver。</p>
<p>所以，不同的浏览器厂商的驱动，对元素的操作可能会存在一些不同的差异，但大体上基本都是没有问题的。</p>
<h3 id="工作原理-1"><a href="#工作原理-1" class="headerlink" title="工作原理"></a>工作原理</h3><p>WebDriver运行时，会调用驱动，在本机上开辟一个端口，来提供端口监听服务。</p>
<p>后续我们在代码里面调用的api，都会像这个端口发送一个<strong>http请求</strong>。</p>
<p>在这个请求的<strong>请求体body</strong>中，会按照WebDriver协议规定的json格式，将我们的api操作封装成一个json字符串进行发送。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python">driver.get(<span class="hljs-string">&quot;http://www.baidu.com&quot;</span>)<br><br><span class="hljs-comment"># 我们阅读get的源码，发现实际上调用的是</span><br><span class="hljs-comment"># self为driver</span><br>self.execute(Command.GET, &#123;<span class="hljs-string">&#x27;url&#x27;</span>: url&#125;)<br></code></pre></td></tr></table></figure>

<p>我们调用上面的代码，会打开百度页面，根据WebDriver协议，会发送一个http request, 请求体body为：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><span class="hljs-attr">&quot;url&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;http://www.baidu.com&quot;</span><span class="hljs-punctuation">&#125;</span>  <br></code></pre></td></tr></table></figure>

<p>所以，所有WebDriver提供的api，都可以追溯到其源码中，来确定它发送的body json。</p>
<h2 id="工作流程"><a href="#工作流程" class="headerlink" title="工作流程"></a>工作流程</h2><ul>
<li>实例化driver，确认驱动版本是否和浏览器版本一致</li>
<li>实例化成功后，会自动分配一个sessionId，代表会话。所以你会发现，每次启动selenium，都是一个无痕浏览器，因为是一个全新的会话。</li>
<li>发送请求，会将<strong>api操作</strong>转化为具体的<strong>url</strong>与<strong>body</strong><ul>
<li>url中会携带sessionId</li>
<li>body中，如果有多种api操作，会自动组合成一个json，不同的操作用不同的<strong>key</strong>作为区分</li>
</ul>
</li>
<li>收到http request并执行，会返回一个http response。这个response中，会包含：<ul>
<li>结果</li>
<li>element的各种属性，比如：class、tag name</li>
<li>操作，比如：send_keys、click</li>
</ul>
</li>
</ul>
<h1 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h1><p>使用前需要安装selenium，并且需要下载对应浏览器版本的驱动。</p>
<blockquote>
<p>pip install selenium</p>
</blockquote>
<blockquote>
<p>谷歌浏览器驱动下载地址：<a target="_blank" rel="noopener" href="https://registry.npmmirror.com/binary.html?path=chromedriver/">https://registry.npmmirror.com/binary.html?path=chromedriver/</a></p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver<br><span class="hljs-keyword">from</span> selenium.webdriver.chrome.service <span class="hljs-keyword">import</span> Service<br><span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By<br><br><span class="hljs-keyword">with</span> webdriver.Chrome(service=Service(<span class="hljs-string">&#x27;./chromedriver.exe&#x27;</span>)) <span class="hljs-keyword">as</span> driver:<br>    driver.get(<span class="hljs-string">&quot;https://www.baidu.com&quot;</span>)<br>    driver.find_element(By.ID, <span class="hljs-string">&quot;kw&quot;</span>).send_keys(<span class="hljs-string">&quot;自动化测试selenium&quot;</span>)<br>    driver.find_element(By.ID, <span class="hljs-string">&quot;su&quot;</span>).click()<br></code></pre></td></tr></table></figure>

<h2 id="with自动销毁"><a href="#with自动销毁" class="headerlink" title="with自动销毁"></a>with自动销毁</h2><p><strong>webdriver.Chrome</strong>通过阅读源码，我们发现，它最终继承祖先类<strong>WebDriver</strong>中，实现了魔法方法：</p>
<ul>
<li>enter</li>
<li>exit</li>
</ul>
<p>满足使用<strong>with</strong>的条件，关于with的使用和原理，可以看博客下的这篇文章：</p>
<blockquote>
<p><a href="https://walker_kwu.gitee.io/my-blog/2022/07/16/python/basic/with/">https://walker_kwu.gitee.io/my-blog/2022/07/16/python/basic/with/</a></p>
</blockquote>
<h2 id="selenium版本的不同"><a href="#selenium版本的不同" class="headerlink" title="selenium版本的不同"></a>selenium版本的不同</h2><p>不同版本的selenium，创建<strong>webdriver.Chrome</strong>和查找元素的方式会不同。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 旧版本</span><br><br><span class="hljs-comment"># 创建driver</span><br>driver = webdriver.Chrome(executable_path=<span class="hljs-string">&#x27;./chromedriver.exe&#x27;</span>)<br><br><span class="hljs-comment"># 根据id查询元素</span><br>driver.find_element_by_id(<span class="hljs-string">&quot;&quot;</span>)<br><br><span class="hljs-comment"># 新版本</span><br><br><span class="hljs-comment"># 创建driver</span><br>driver = webdriver.Chrome(service=Service(<span class="hljs-string">&#x27;./chromedriver.exe&#x27;</span>))<br><br><span class="hljs-comment"># 根据id查询元素</span><br>driver.find_element(By.ID, <span class="hljs-string">&quot;&quot;</span>)<br></code></pre></td></tr></table></figure>

<h2 id="查找元素有哪几种方法"><a href="#查找元素有哪几种方法" class="headerlink" title="查找元素有哪几种方法"></a>查找元素有哪几种方法</h2><p>以下为selenium的源码内容</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">By</span>:<br>    <span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    Set of supported locator strategies.</span><br><span class="hljs-string">    &quot;&quot;&quot;</span><br><br>    ID = <span class="hljs-string">&quot;id&quot;</span><br>    XPATH = <span class="hljs-string">&quot;xpath&quot;</span><br>    LINK_TEXT = <span class="hljs-string">&quot;link text&quot;</span><br>    PARTIAL_LINK_TEXT = <span class="hljs-string">&quot;partial link text&quot;</span><br>    NAME = <span class="hljs-string">&quot;name&quot;</span><br>    TAG_NAME = <span class="hljs-string">&quot;tag name&quot;</span><br>    CLASS_NAME = <span class="hljs-string">&quot;class name&quot;</span><br>    CSS_SELECTOR = <span class="hljs-string">&quot;css selector&quot;</span><br></code></pre></td></tr></table></figure>

<p>其中推荐指数，由上到下，依次递减：</p>
<ul>
<li>ID</li>
<li>CSS_SELECTOR</li>
<li>CLASS_NAME</li>
<li>XPATH</li>
</ul>
<h1 id="自动化-PO模式"><a href="#自动化-PO模式" class="headerlink" title="自动化-PO模式"></a>自动化-PO模式</h1><p>PO模式，全称 Page Object。</p>
<p>意思就是，将一个页面的所有操作当作一个类对象来看待。</p>
<p>封装好一个页面之后，需要用到这个页面的操作，就从封装好的类中取。</p>
<p>举例：新建baidu.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> selenium.webdriver.common.by <span class="hljs-keyword">import</span> By<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">BaiDu</span>():<br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, driver</span>):<br>        self.driver = driver<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">searchInput</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-keyword">return</span> self.driver.find_element(By.ID, <span class="hljs-string">&quot;kw&quot;</span>)  <span class="hljs-comment"># 搜索框</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">searchButton</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-keyword">return</span> self.driver.find_element(By.ID, <span class="hljs-string">&quot;su&quot;</span>)  <span class="hljs-comment"># “百度一下“按钮</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">searchSendText</span>(<span class="hljs-params">self, text</span>):  <span class="hljs-comment"># 向搜索框中输入文字</span><br>        self.searchInput().clear()  <span class="hljs-comment"># 清空文字</span><br>        self.searchInput().send_keys(text)  <span class="hljs-comment"># 输入文字</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">searchConfirm</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 确定搜索</span><br>        self.searchButton().click()  <span class="hljs-comment"># 点击“百度一下”</span><br>        <br></code></pre></td></tr></table></figure>

<h1 id="面试常问"><a href="#面试常问" class="headerlink" title="面试常问"></a>面试常问</h1><h2 id="iframe切换"><a href="#iframe切换" class="headerlink" title="iframe切换"></a>iframe切换</h2><blockquote>
<p>driver.switch_to.frame(‘’)</p>
</blockquote>
<h2 id="工作原理（不算常问，但很重要很加分）"><a href="#工作原理（不算常问，但很重要很加分）" class="headerlink" title="工作原理（不算常问，但很重要很加分）"></a>工作原理（不算常问，但很重要很加分）</h2><h2 id="显式等待、隐式等待、强制等待的使用和区别"><a href="#显式等待、隐式等待、强制等待的使用和区别" class="headerlink" title="显式等待、隐式等待、强制等待的使用和区别"></a>显式等待、隐式等待、强制等待的使用和区别</h2><h3 id="显式等待"><a href="#显式等待" class="headerlink" title="显式等待"></a>显式等待</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> selenium.webdriver.support.ui <span class="hljs-keyword">import</span> WebDriverWait<br><span class="hljs-keyword">from</span> selenium.webdriver.support <span class="hljs-keyword">import</span> expected_conditions <span class="hljs-keyword">as</span> EC<br>element = WebDriverWait(driver, <span class="hljs-number">10</span>, <span class="hljs-number">0.5</span>).until(EC.visibility_of_element_located((By.ID, <span class="hljs-string">&#x27;su&#x27;</span>)))<br></code></pre></td></tr></table></figure>

<p>针对于某个特定的元素设置的等待时间，在设置时间内，默认每隔0.5时间检测一次特定的元素是否存在，</p>
<p>如果在设置的时间内找到了元素，则直接执行。如果超过设置最长等待时间(上面的代码的等待时间为10秒)检测不到则报错。</p>
<h3 id="隐式等待"><a href="#隐式等待" class="headerlink" title="隐式等待"></a>隐式等待</h3><blockquote>
<p>driver.implicitly_wait(5)</p>
</blockquote>
<p>全局生效，只需要定义一次，作用到每次寻找元素的步骤中。</p>
<p>在5秒内，以轮询的方式不断寻找元素，找到的话，就中止查找，继续执行下一步，如果5秒内都没有找到，会报错。</p>
<h3 id="强制等待"><a href="#强制等待" class="headerlink" title="强制等待"></a>强制等待</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> time<br><br>time.sleep(<span class="hljs-number">5</span>)<br></code></pre></td></tr></table></figure>

<p>让程序整体停止5秒，不管有没有找到元素，都要等待5秒。</p>
<p>当显式等待、隐式等待都无法解决你的问题的时候，再使用这个。</p>
<h2 id="最常用的定位方法，哪种最优"><a href="#最常用的定位方法，哪种最优" class="headerlink" title="最常用的定位方法，哪种最优"></a>最常用的定位方法，哪种最优</h2><p>文中有说明</p>
<h2 id="selenium自动化页面元素找不到存在异常的原因"><a href="#selenium自动化页面元素找不到存在异常的原因" class="headerlink" title="selenium自动化页面元素找不到存在异常的原因"></a>selenium自动化页面元素找不到存在异常的原因</h2><ul>
<li>元素定位错误</li>
<li>页面加载时间过慢，需要查找的元素程序已经完成，单页面还未加载，此时可以加载页面等待时间</li>
<li>有可能元素包含在iframe或者frame里面，需要切换。</li>
</ul>
<h2 id="PO模式"><a href="#PO模式" class="headerlink" title="PO模式"></a>PO模式</h2><p>文中有说明</p>
<h2 id="调用js-execute-script-有哪些应用场景"><a href="#调用js-execute-script-有哪些应用场景" class="headerlink" title="调用js(execute_script), 有哪些应用场景"></a>调用js(execute_script), 有哪些应用场景</h2><ul>
<li>滚动屏幕</li>
<li>对富文本框的操作</li>
<li>元素高亮</li>
<li>判断元素内容</li>
<li>无法通过click点击的元素，但是需要进行点击</li>
<li>显示隐藏元素</li>
</ul>
<h2 id="如何判断元素是否查找得到"><a href="#如何判断元素是否查找得到" class="headerlink" title="如何判断元素是否查找得到"></a>如何判断元素是否查找得到</h2><ul>
<li>try … except</li>
<li>find_elements，会返回一个数组，如果数组长度为0，则为没有查找到</li>
</ul>
<h2 id="隐藏元素定位到了，无法操作"><a href="#隐藏元素定位到了，无法操作" class="headerlink" title="隐藏元素定位到了，无法操作"></a>隐藏元素定位到了，无法操作</h2><p>可以用js 将元素的 display:none 修改成 display: block </p>
<h2 id="截图"><a href="#截图" class="headerlink" title="截图"></a>截图</h2><blockquote>
<p>driver.get_screenshot_as_file()</p>
</blockquote>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/" class="category-chain-item">自动化测试</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/selenium/" class="category-chain-item">selenium</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/">#自动化测试</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/WebUI%E8%87%AA%E5%8A%A8%E5%8C%96/">#WebUI自动化</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>selenium--最为流行的WebUI自动化工具库</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/09/18/autoTest/selenium/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年9月18日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/09/20/notes/js/jsIntroduction/" title="javascript简介">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">javascript简介</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/09/16/notes/css/layoutRule/" title="布局细则">
                        <span class="hidden-mobile">布局细则</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
